 
package com.zdkj.subway.rca.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zdkj.subway.rca.entity.ViewCkOperatorsRemitCat;
import com.zdkj.subway.rca.mapper.ViewCkOperatorsRemitCatMapper;
import com.zdkj.subway.rca.service.ViewCkOperatorsRemitCatService;
import com.zdkj.subway.rca.util.LocalDateConverter;
import com.zdkj.subway.rca.util.LocalDateTimeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * VIEW
 *
 * @author stw
 * @date 2020-12-16 13:56:53
 */
@Service
public class ViewCkOperatorsRemitCatServiceImpl extends ServiceImpl<ViewCkOperatorsRemitCatMapper, ViewCkOperatorsRemitCat> implements ViewCkOperatorsRemitCatService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ViewCkOperatorsRemitCatServiceImpl.class);
    @Override
    public List<ViewCkOperatorsRemitCat> listViewCkOperatorsRemitCat(String startDate, String endDate, String operators) {

        List<ViewCkOperatorsRemitCat> list = this.baseMapper.listViewCkOperatorsRemitCat(startDate,endDate,operators);
		List<ViewCkOperatorsRemitCat> listXixian = this.baseMapper.listViewCkOperatorsRemitCatForXixian(startDate,endDate);
        ViewCkOperatorsRemitCat sumSubTotal  = getSum("西咸小计",null,listXixian,true);
		ViewCkOperatorsRemitCat sumAll  = getSum("合计",list,listXixian,true);
		list.addAll(listXixian);
		list.add(sumSubTotal);
        list.add(sumAll);
        return list;
    }

    private ViewCkOperatorsRemitCat getSum(String operatorsName,List<ViewCkOperatorsRemitCat> list,List<ViewCkOperatorsRemitCat> listXixian,boolean flag){
        ViewCkOperatorsRemitCat sumViewCkOperatorsRemitCat = new ViewCkOperatorsRemitCat();
        sumViewCkOperatorsRemitCat.setOperatorsName(operatorsName);
        sumViewCkOperatorsRemitCat.setOperators(operatorsName);


        BigDecimal catSystemClean = new BigDecimal("0");
        BigDecimal trafficCardSystemClean = new BigDecimal("0");
        BigDecimal catPaySubtotal = new BigDecimal("0");
        BigDecimal remitCat = new BigDecimal("0");
        BigDecimal remitTrafficCard = new BigDecimal("0");
        BigDecimal catRemitSubtotal = new BigDecimal("0");

        //
        //第一个sheet组织数据
		if(flag){
		  if(operatorsName.equals("西咸小计")){
		   for(ViewCkOperatorsRemitCat  obj : listXixian){            
                catSystemClean = catSystemClean.add(obj.getCatSystemClean());
                trafficCardSystemClean = trafficCardSystemClean.add(obj.getTrafficCardSystemClean());
                catPaySubtotal = catPaySubtotal.add(obj.getCatPaySubtotal());
                remitCat = remitCat.add(obj.getRemitCat());
                remitTrafficCard = remitTrafficCard.add(obj.getRemitTrafficCard());
                catRemitSubtotal = catRemitSubtotal.add(obj.getCatRemitSubtotal());
           }
			
			}else{		   
				
				for(ViewCkOperatorsRemitCat  obj : list){            
					catSystemClean = catSystemClean.add(obj.getCatSystemClean());
					trafficCardSystemClean = trafficCardSystemClean.add(obj.getTrafficCardSystemClean());
					catPaySubtotal = catPaySubtotal.add(obj.getCatPaySubtotal());
					remitCat = remitCat.add(obj.getRemitCat());
					remitTrafficCard = remitTrafficCard.add(obj.getRemitTrafficCard());
					catRemitSubtotal = catRemitSubtotal.add(obj.getCatRemitSubtotal());           
			   }
			   for(ViewCkOperatorsRemitCat  obj : listXixian){            
					catSystemClean = catSystemClean.add(obj.getCatSystemClean());
					trafficCardSystemClean = trafficCardSystemClean.add(obj.getTrafficCardSystemClean());
					catPaySubtotal = catPaySubtotal.add(obj.getCatPaySubtotal());
					remitCat = remitCat.add(obj.getRemitCat());
					remitTrafficCard = remitTrafficCard.add(obj.getRemitTrafficCard());
					catRemitSubtotal = catRemitSubtotal.add(obj.getCatRemitSubtotal());
			   }
			}
		}else{
		   for(ViewCkOperatorsRemitCat  obj : list){            
					catSystemClean = catSystemClean.add(obj.getCatSystemClean());
					trafficCardSystemClean = trafficCardSystemClean.add(obj.getTrafficCardSystemClean());
					catPaySubtotal = catPaySubtotal.add(obj.getCatPaySubtotal());				    
			 }
		   
		}
		
        sumViewCkOperatorsRemitCat.setCatSystemClean(catSystemClean.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkOperatorsRemitCat.setTrafficCardSystemClean(trafficCardSystemClean.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkOperatorsRemitCat.setCatPaySubtotal(catPaySubtotal.setScale(2,BigDecimal.ROUND_HALF_UP));
        if(flag){
		   sumViewCkOperatorsRemitCat.setRemitCat(remitCat.setScale(2,BigDecimal.ROUND_HALF_UP));
           sumViewCkOperatorsRemitCat.setRemitTrafficCard(remitTrafficCard.setScale(2,BigDecimal.ROUND_HALF_UP));
           sumViewCkOperatorsRemitCat.setCatRemitSubtotal(catRemitSubtotal.setScale(2,BigDecimal.ROUND_HALF_UP));
		}
		
        return sumViewCkOperatorsRemitCat;
    }
   private List<ViewCkOperatorsRemitCat> listViewCkOperatorsRemitCatFor9Line(String startDate, String endDate) {

        List<ViewCkOperatorsRemitCat> list = this.baseMapper.listViewCkOperatorsRemitCatFor9Line(startDate,endDate);
		
        ViewCkOperatorsRemitCat sumAll  = getSum("合计",list,null,false);
        list.add(sumAll);
        return list;
    }
	
	 public void export(String startDate,String endDate,String operators,HttpServletResponse response) {

        List<ViewCkOperatorsRemitCat> records = listViewCkOperatorsRemitCat(startDate,endDate,operators);
		List<ViewCkOperatorsRemitCat> recordsFor9 = listViewCkOperatorsRemitCatFor9Line(startDate,endDate);        
        
        InputStream excelTemplateIs = null;
        try {response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode("运营商划账（长安通卡)", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");

            // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
            // {} 代表普通变量 {.} 代表是list的变量

           excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/template/export/ViewCkOperatorsRemitCatExcelTemplate.xlsx");

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplateIs).build();
            Map<String, Object> map = new HashMap<>();
            map.put("beginTime", startDate);
            map.put("endTime", endDate);
            if(CollectionUtils.isNotEmpty(records)){
                WriteSheet writeSheet = EasyExcel.writerSheet(0,"运营商划账（长安通卡消费)").build();
                // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
                // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
                // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
                // 如果数据量大 list不是最后一行 参照另一个
                FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
                excelWriter.fill(records, fillConfig, writeSheet);
                excelWriter.fill(map, writeSheet);
            }
            if(CollectionUtils.isNotEmpty(recordsFor9)){
                WriteSheet writeSheet = EasyExcel.writerSheet(1,"运营商划账（长安通卡充值)").build();
                // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
                // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
                // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
                // 如果数据量大 list不是最后一行 参照另一个
                FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
                excelWriter.fill(recordsFor9, fillConfig, writeSheet);
                excelWriter.fill(map, writeSheet);
            }

            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("导出运营商划账（长安通卡)异常");
        } finally {
            if(excelTemplateIs != null){
                try {
                    excelTemplateIs.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }
	
}
